import { RedisService } from "@midwayjs/redis";
import { Provide,Inject } from '@midwayjs/decorator';
import { WechatOaSDK, WechatSamllSDK } from "../base/WechatSDK";
import { IWechatConfigItem, IWechatLoginData, IWechatToken } from "../interfaces/IWechat.interface";
import { DBBase } from "../base/DBBase";
import { SystemConfigService } from "./system.service";
import { SystemConfigType } from "../interfaces/ISystem.interface";
import { ErrCode } from "../common/ErrCode";

@Provide()
export class WechatService extends DBBase{

    @Inject()
    redisSerice:RedisService;

    @Inject()
    systemConfig:SystemConfigService;

    // private oa
    private oa:WechatOaSDK;// = new WechatOaSDK({OAappid:"",OAsecret:""});

    private small:WechatSamllSDK;//new WechatSamllSDK({appid:"wxe918beb29b2be698",secret:"63e79b77a801f482ed808bdfe0a6e782"});


    private async init():Promise<ErrCode>{
        let config:IWechatConfigItem = await this.systemConfig.getSystemConfig(SystemConfigType.Wechat_Config);
        if(this.small == null && config != null){
            if(config.smallAppid == null || config.smallAppid == ""){
                return ErrCode.SYSTEM_CONFIG_NULL;
            }
            this.small = new WechatSamllSDK({appid:config.smallAppid,secret:config.smallSecret});
        }
        if(this.oa == null){
            if(config.OAappid == null || config.OAappid == ""){
                return ErrCode.SYSTEM_CONFIG_NULL;
            }
            this.oa = new WechatOaSDK({appid:config.OAappid,secret:config.OAsecret});
           
        }
        return ErrCode.SYSTEM_SUCCESS;
    }

    public async SmallLogin(code:string):Promise<IWechatLoginData|ErrCode>{
        let errcode:ErrCode = await this.init();
        if(errcode == ErrCode.SYSTEM_SUCCESS){
            return await this.small.login(code);
        }
        return errcode;
    }

    public async OAgetCodeUrl(url:string,scope:string):Promise<string|ErrCode>{
        let errcode:ErrCode = await this.init();
        if(errcode == ErrCode.SYSTEM_SUCCESS){
            return await this.oa.getCode(url,scope);
        }
        return errcode;
    }

    public async OALogin(code:string):Promise<IWechatToken|ErrCode>{
        let errcode:ErrCode = await this.init();
        if(errcode == ErrCode.SYSTEM_SUCCESS){
            return await this.oa.getOpenid(code);
        }
        return errcode;
    }
}